import React, { useEffect, useState } from "react";
import {
  Button,
  Table,
  Modal,
  Form,
  Input,
  Space,
  Popconfirm,
  message,
  DatePicker,
  Pagination,
  Select,
  Card,
  Typography,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import moment from "moment";
import { taskApi, subjectApi } from "../../services/api";

const { Title } = Typography;

interface Task {
  id: number;
  name: string;
  content: string;
  detail: string;
  status: string;
  createTime: string;
  endTime: string;
  subjectId: number;
}

interface Subject {
  id: number;
  name: string;
}

const TaskPage: React.FC = () => {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [subjects, setSubjects] = useState<Subject[]>([]);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState<number | null>(null);
  const [pageTotal, setPageTotal] = useState<number>(0);
  const [subjectPageTotal, setSubjectPageTotal] = useState<number>(0);

  const columns: ColumnsType<Task> = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "任务名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "内容",
      dataIndex: "content",
      key: "content",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      render: (text: string) => moment(text).format("YYYY-MM-DD HH:mm:ss"),
    },
    {
      title: "结束时间",
      dataIndex: "endTime",
      key: "endTime",
      render: (text: string) => moment(text).format("YYYY-MM-DD HH:mm:ss"),
    },
    {
      title: "课程ID",
      dataIndex: "subjectId",
      key: "subjectId",
    },
    {
      title: "课程名称",
      dataIndex: "subjectName",
      key: "subjectName",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => handleEdit(record)}>编辑</a>
          <Popconfirm
            title="确定删除此任务吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const fetchTasks = async () => {
    setLoading(true);
    try {
      const response = await taskApi.selectAll();
      setTasks(response.data || []);
    } catch (error) {
      message.error("获取任务列表失败");
    } finally {
      setLoading(false);
    }
  };

  const fetchSubjects = async (current = 1, pageSize = 1000) => {
    try {
      const response = await subjectApi.selectPage({
        pageNum: current,
        pageSize,
      });
      setSubjects(response.data.list || []);
      setSubjectPageTotal(response.data.total);
    } catch (error) {
      message.error("获取课程列表失败");
    }
  };

  const handleEdit = (record: Task) => {
    setEditingId(record.id);
    form.setFieldsValue({
      ...record,
      createTime: record.createTime ? moment(record.createTime) : null,
      endTime: record.endTime ? moment(record.endTime) : null,
    });
    setOpen(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await taskApi.delete(id);
      message.success("删除成功");
      fetchTasks();
    } catch (error) {
      message.error("删除失败");
    }
  };

  const handleAdd = () => {
    setEditingId(null);
    form.resetFields();
    setOpen(true);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      // 格式化时间
      if (values.createTime) {
        values.createTime = values.createTime.format("YYYY-MM-DD HH:mm:ss");
      }
      if (values.endTime) {
        values.endTime = values.endTime.format("YYYY-MM-DD HH:mm:ss");
      }

      if (editingId) {
        await taskApi.update({ ...values, id: editingId });
        message.success("更新成功");
      } else {
        await taskApi.add(values);
        message.success("添加成功");
      }
      setOpen(false);
      fetchTasks();
    } catch (error) {
      message.error("操作失败");
    }
  };

  const handleCancel = () => {
    setOpen(false);
  };

  const fetchTasksByPage = async (current: number, pageSize: number) => {
    setLoading(true);
    try {
      const response = await taskApi.selectPage({
        pageNum: current,
        pageSize,
      });
      setTasks(response.data.list || []);
      setPageTotal(response.data.total);
    } catch (error) {
      message.error("获取任务列表失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTasksByPage(1, 10);
    fetchSubjects();
  }, []);

  function onShowSizeChange(current: number, size: number): void {
    // 分页查询逻实现
    fetchTasksByPage(current, size);
  }

  return (
    <div>
      <Card 
        title={<Title level={4} style={{ margin: 0, color: '#0052D9' }}>任务管理</Title>}
        extra={
          <Button type="primary" onClick={handleAdd}>
            添加任务
          </Button>
        }
        style={{ padding: 0 }}
      >
        <Table
          columns={columns}
          dataSource={tasks}
          loading={loading}
          rowKey="id"
          pagination={false}
        />
        
        <div style={{ padding: '16px', display: 'flex', justifyContent: 'flex-end' }}>
          <Pagination
            showSizeChanger
            onShowSizeChange={onShowSizeChange}
            defaultCurrent={1}
            total={pageTotal}
            onChange={fetchTasksByPage}
            showTotal={(total) => `共 ${total} 条记录`}
          />
        </div>
      </Card>

      <Modal
        title={editingId ? "编辑任务" : "添加任务"}
        open={open}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
        width={800}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="任务名称"
            rules={[{ required: true, message: "请输入任务名称" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item name="content" label="内容">
            <Input.TextArea />
          </Form.Item>

          <Form.Item name="detail" label="详情">
            <Input.TextArea />
          </Form.Item>

          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态">
              <Select.Option value="待开始">未开始</Select.Option>
              <Select.Option value="进行中">进行中</Select.Option>
              <Select.Option value="已结束">已完成</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item name="createTime" label="创建时间">
            <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
          </Form.Item>

          <Form.Item name="endTime" label="结束时间">
            <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
          </Form.Item>

          <Form.Item
            name="subjectId"
            label="课程"
            rules={[{ required: true, message: "请选择课程" }]}
          >
            <Select
              showSearch
              placeholder="请选择课程"
              optionFilterProp="children"
              filterOption={(input, option) =>
                (option?.children as unknown as string)
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            >
              {subjects.map((subject) => (
                <Select.Option key={subject.id} value={subject.id}>
                  {subject.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default TaskPage;